package com.zzyl.intercept;

import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstants;
import com.zzyl.constant.Constants;
import com.zzyl.properties.JwtTokenProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.MgtThreadLocal;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class ManagerLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtTokenProperties jwtTokenProperties;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的token
        String token = request.getHeader(Constants.USER_TOKEN);
        // 判断token是否存在
        if (StrUtil.isEmpty(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        // 解析token，校验
        Claims claims = JwtUtil.parseJWT(jwtTokenProperties.getSecretKey(), token);
        String userInfo_json = claims.get(Constants.JWT_USERINFO, String.class);
        // 根据用户id获取redis中可访问权限列表
        JSONObject jsonObject = JSONUtil.parseObj(userInfo_json);
        Long userid = jsonObject.getLong("id");
        String json = redisTemplate.opsForValue().get(CacheConstants.ACCESS_URLS + userid);
        if (StrUtil.isEmpty(json)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        List<String> accessList = JSONUtil.toList(json, String.class);
        String path = request.getMethod() + request.getRequestURI();
        // 匹配流中的任意一个元素返回true
        boolean anyMatch = accessList.stream().anyMatch(access -> antPathMatcher.match(access, path));
        if (!anyMatch) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return false;
        }
        // 校验通过。保存用户信息到ThreadLocal中
        MgtThreadLocal.set(userInfo_json);
        // 放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        MgtThreadLocal.remove();
    }
}
